<template>
	<view class="tupu-content" ref="chartContainer">
		<!-- 使用renderjs -->
		<view :prop="option" :change:prop="echarts.update" class="echarts" id="echarts"></view>

		<!-- 自定义弹框 -->
		<view v-if="popupVisible" class="custom-popup" :style="{ left: 0 + 'px', top: (100+StatusBarRpx)+'rpx' }">
			<view class="title">{{kuangObj.name}} </view>
			<view class="number-outer">
				关联资源：<text style="margin-right: 60rpx;">{{kuangObj.ziyuan}}</text>
				关联习题：<text>{{kuangObj.xiti}}</text>
			</view>
			<view class="operate">
				学习进度：<text style="font-weight: bold;font-size: 28rpx;color: #31CA91;">{{kuangObj.rate }}%</text>
				<text class="go-sch" @click="goNext">去学习 ></text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			aid: String,
			nameTitle: String
		},
		data() {
			return {
				option: {
					color: [],
					series: [{
						name: "知识图谱",
						type: "graph",
						layout: "force",
						force: {
							repulsion: 260,
							edgeLength: [80, 200],
							gravity: 0.1,
						},
						nodeScaleRatio: 0.6,
						draggable: true,
						roam: true,
						symbol: "circle",
						data: [],
						links: [],
						focusNodeAdjacency: true,
						scaleLimit: {
							min: 0.5,
							max: 9
						},
						edgeSymbol: ["circle"],
						edgeSymbolSize: [4, 8],
						label: {
							show: true,
							position: "right",
							color: "#fff",
							distance: 5,
							fontSize: 10,
						},
						lineStyle: {
							width: 1.5,
							curveness: 0,
							type: "solid",
						},
					}]
				},
				popupVisible: false,
				popupPosition: {
					x: 0,
					y: 0
				},
				kuangObj: {
					rate: "",
					xiti: "",
					ziyuan: "",
					name: "",
					aid: ""
				},
				colors: [{
						c1: "#145EFD",
						c2: "#4B8AFF"
					},
					{
						c1: "#31CA91",
						c2: "#5EE0B3"
					},
					{
						c1: "#FFB800",
						c2: "#FFD152"
					},
					{
						c1: "#FF7D00",
						c2: "#FF9D3F"
					},
					{
						c1: "#EE3B3B",
						c2: "#FF6B6B"
					},
					{
						c1: "#8A2BE2",
						c2: "#A569BD"
					},
					{
						c1: "#1E90FF",
						c2: "#6495ED"
					},
					{
						c1: "#3CB371",
						c2: "#2E8B57"
					}
				]
			};
		},
		mounted() {
			this.get_textbookchapter_info();
		},
		methods: {
			async get_textbookchapter_info() {
				let res = await this.$api.post(global.apiUrls.post680ef2551be54, {
					aid: this.aid,
				});

				if (res.data.code == 1) {
					const arr = [{
						"title": this.nameTitle,
						"value": this.nameTitle,
						"children": res.data.data
					}];

					// 处理数据
					const legendColor = this.colors.map(item => item.c2);
					const {
						nodes,
						links
					} = this.processData(arr);

					this.option.color = legendColor;
					this.option.series[0].data = nodes;
					this.option.series[0].links = links;
				}
			},

			processData(arr, idx = 0, category = null) {
				const nodes = [];
				const links = [];

				const process = (data, level = 0) => {
					data.forEach(item => {
						// 节点大小
						let symbolSize = 80;
						if (level == 0) symbolSize = 130;
						else if (item.is_zhishidian) symbolSize = 80;
						else symbolSize = 100;

						// 节点图标
						let symbol = "circle";
						if (level == 0) {
							symbol = "image://static/img02/zhang.png";
						} else if (item.is_zhishidian) {
							if (item.rate == 0) {
								symbol = "image://static/img02/dian0.png";
							} else if (item.rate == 100) {
								symbol = "image://static/img02/dian100.png";
							} else {
								symbol = "image://static/img02/dian.png";
							}
						} else {
							symbol = "image://static/img02/jie.png";
						}

						// 节点数据
						nodes.push({
							name: item.title,
							value: item.aid,
							symbolSize,
							symbol,
							category,
							title: item.title,
							aid: item.aid,
							is_zhishidian: item.is_zhishidian,
							label: {
								show: true,
								position: "inside",
								formatter: this.wrapText(item.title, symbolSize),
								fontSize: 11,
								lineHeight: 14,
								color: "#fff"
							}
						});

						// 处理子节点
						if (item.children) {
							item.children.forEach(child => {
								links.push({
									source: item.title,
									target: child.title,
									lineStyle: {
										color: "rgba(57, 81, 129, 1)"
									}
								});
								process([child], level + 1);
							});
						}
					});
				};

				process(arr);
				return {
					nodes,
					links
				};
			},

			// 文本换行处理
			wrapText(text, symbolSize, fontSize = 12) {
				const maxChars = Math.floor(symbolSize * 0.5 / (fontSize * 0.6));
				const lines = [];
				for (let i = 0; i < text.length; i += maxChars) {
					lines.push(text.slice(i, i + maxChars));
				}
				return lines.join("\n");
			},

			// 跳转到知识点
			goNext() {
				this.$urouter.navigateTo(
					`/pages/course/knowledgePoints/knowledgePoints?aid=${this.kuangObj.aid}`
				);
			},

			// 处理节点点击事件
			handleNodeClick(data) {
				this.kuangObj = {
					name: data.name,
					aid: data.aid,
					rate: "",
					xiti: "",
					ziyuan: ""
				};

				// 计算弹窗位置
				// this.popupPosition = this.calculatePopupPosition(data.event);

				// 获取知识点详情
				this.get_zhishidian_infoApi(data.aid);
			},

			// 获取知识点详情
			async get_zhishidian_infoApi(aid) {
				let res = await this.$api.post(global.apiUrls.post680ef68106993a1c62, {
					aid
				});
				if (res.data.code == 1) {
					this.kuangObj = {
						...res.data.data,
						name: this.kuangObj.name,
						aid: this.kuangObj.aid
					};
					this.popupVisible = true;
				}
			},

			// 处理点击位置计算
			calculatePopupPosition(event) {
				const systemInfo = uni.getSystemInfoSync();
				const windowWidth = systemInfo.windowWidth;
				const windowHeight = systemInfo.windowHeight;

				// 获取图表容器的位置信息
				const query = uni.createSelectorQuery().in(this);
				query.select('.echarts').boundingClientRect(data => {
					const chartRect = data;

					// 弹窗尺寸（px）
					const popupWidth = 236; // 472rpx / 2
					const popupHeight = 135; // 270rpx / 2

					// 计算点击位置相对于图表容器的坐标
					let clickX = event.clientX - chartRect.left;
					let clickY = event.clientY - chartRect.top;

					// 计算弹窗位置（确保不会超出图表容器边界）
					let popupX = clickX + 10;
					let popupY = clickY + 10;

					// 检查右边界
					if (popupX + popupWidth > chartRect.width) {
						popupX = clickX - popupWidth - 10;
					}

					// 检查下边界
					if (popupY + popupHeight > chartRect.height) {
						popupY = clickY - popupHeight - 10;
					}

					// 确保位置不小于0
					popupX = Math.max(0, popupX);
					popupY = Math.max(0, popupY);

					// 转换为相对于页面的绝对位置
					this.popupPosition = {
						x: popupX + chartRect.left,
						y: popupY + chartRect.top
					};
				}).exec();

				// 返回一个默认位置，实际位置会在回调中更新
				return {
					x: event.clientX,
					y: event.clientY
				};
			}
		}
	};
</script>

<script module="echarts" lang="renderjs">
	import * as echarts from 'echarts';
	let chart = null;

	export default {
		mounted() {
			this.init();
			// if (typeof window.echarts === 'function') {

			// } else {
			// 	const script = document.createElement('script');
			// 	script.src = 'https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js';
			// 	script.onload = this.init;
			// 	document.head.appendChild(script);
			// }
		},
		methods: {
			handlePopupVisible(visible) {
				this.$nextTick(() => {
					this.popupVisible = visible;
				})
			},
			init() {
				chart = echarts.init(document.getElementById('echarts'));
				this.update(this.option);

				// 点击事件处理
				chart.on('click', (params) => {
					console.log('7777777777777777', params);
					if (!params.data || !params.data.is_zhishidian) {
						this.$ownerInstance.callMethod('handlePopupVisible', false);
						return;
					}

					// 传递点击数据给Vue组件
					this.$ownerInstance.callMethod('handleNodeClick', {
						name: params.data.title,
						aid: params.data.aid,
						event: params.event.event
					});
				});
			},
			update(newOption) {
				if (chart) chart.setOption(newOption);
			},
			resize() {
				if (chart) chart.resize();
			}
		}
	};
</script>

<style scoped>
	.tupu-content {
		height: 100%;
		width: 100%;
		position: relative;
	}

	.echarts {
		width: 100%;
		height: 100%;
		min-height: 600rpx;
		position: relative;
	}

	.custom-popup {
		position: fixed;
		width: 472rpx;
		height: 270rpx;
		background: linear-gradient(180deg, #CEE0FF 0%, #FFFFFF 37%, #FFFFFF 100%);
		border-radius: 12rpx;
		border: 1rpx solid #EEEEEE;
		z-index: 999;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		transform: translateZ(0);
		/* 解决某些浏览器下的渲染问题 */
	}

	.title {
		font-weight: 600;
		font-size: 30rpx;
		color: #131D34;
		margin-top: 24rpx;
		margin-left: 32rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		width: 400rpx;
	}

	.number-outer {
		margin-top: 42rpx;
		margin-left: 32rpx;
		font-size: 26rpx;
		color: #747E96;
	}

	.operate {
		margin-top: 47rpx;
		margin-left: 32rpx;
		font-size: 26rpx;
		color: #747E96;
		display: flex;
		align-items: center;
	}

	.go-sch {
		display: inline-block;
		width: 140rpx;
		height: 48rpx;
		background: #145EFD;
		border-radius: 8rpx;
		font-size: 24rpx;
		color: #FFFFFF;
		line-height: 48rpx;
		text-align: center;
		margin-left: 40rpx;
		cursor: pointer;
	}
</style>